//
//  FinalViewController.m
//  KeepFit
//
//  Created by dllo on 15/10/31.
//  Copyright © 2015年 Fuzzie Liu. All rights reserved.
//

#import "FinalViewController.h"
#import "FoodDetail.h"
#import <MBProgressHUD.h>
#import "Compare.h"
#import "Ingredient.h"
#import "IntroduceCell.h"
#import "CompareTableViewCell.h"
#import "IngredientTableViewCell.h"
#import <FMDB.h>
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDKUI.h>
#import "UILabel+NightVersion.h"
@interface FinalViewController ()<UITableViewDataSource, UITableViewDelegate,MBProgressHUDDelegate>
@property (nonatomic, strong) FoodDetail *finalFood;
@property (nonatomic, strong) Compare *foodCompare;
@property (nonatomic, strong) Ingredient *foodImgredient;
@property (nonatomic, strong) UITableView *finalTableView;
@property (nonatomic, strong) NSMutableArray *bigArr;
// 能量数组 数值的
@property (nonatomic, strong) NSMutableArray *energyArr;
// 分区2 中文名字数组
@property (nonatomic, strong) NSArray *foodChineseArr;
// 单位
@property (nonatomic, strong) NSArray *danWeiArr;
@property (nonatomic, strong) NSMutableArray *remarkArr;
@property (nonatomic, strong) UIImageView *foodImageView;
@property (nonatomic, strong) UILabel *nameLab;
@property (nonatomic, strong) UILabel *energyLab;
@property (nonatomic, assign) BOOL isCompareing;

@property (nonatomic, strong) FMDatabase *foodDB;
@property (nonatomic, assign) BOOL isCollection;
@property (nonatomic, strong) UIBarButtonItem *item1;
@property (nonatomic, strong) UIBarButtonItem *item2;
@end

@implementation FinalViewController


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *fileName = [doc stringByAppendingPathComponent:@"KeepFit.sqlite"];
    self.foodDB = [FMDatabase databaseWithPath:fileName];
    NSLog(@"%@",fileName);
    if ([self.foodDB open]) {
        BOOL result = [self.foodDB executeUpdate:@"create table if not exists t_foodDetail (code text PRIMARY KEY , name text NOT NULL, thumb_image_url text NOT NULL);"];
        if (result) {
            NSLog(@"创表成功");
        }else
        {
            NSLog(@"创表失败");
        }
    }
     self.item2 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-share@2x.png"] style:UIBarButtonItemStyleDone target:self action:@selector(rightBarButtonAction2:)];
    
    
    FMResultSet *resultSet = [self.foodDB executeQuery:@"select * from t_foodDetail where code = ?;",self.foodCode];
    if (resultSet.next == NO) {
        self.isCollection = NO;
//        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-aa@3x.png"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonAction:)];
        self.item1 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-aa@3x.png"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonAction:)];
        
    }else
    {
        self.isCollection = YES;
        UIImage *image = [UIImage imageNamed:@"iconfont-aa-2@3x.png"];
        image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStyleDone target:self action:@selector(rightBarButtonAction:)];
        self.item1 = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStyleDone target:self action:@selector(rightBarButtonAction:)];
        
    }
    self.navigationItem.rightBarButtonItems = @[self.item1,self.item2];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"%@",_finalFood.name);
     self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fanhui@2x.png"] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarButtonAction:)];
   
    self.view.backgroundColor = [UIColor redColor];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width - 64, 100)];

    self.foodImageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, view.bounds.size.height - 10, view.bounds.size.height - 10)];
    self.foodImageView.layer.cornerRadius = 5;
    self.foodImageView.layer.masksToBounds = YES;
    [view addSubview:self.foodImageView];
    
    self.nameLab = [[UILabel alloc] initWithFrame:CGRectMake(self.foodImageView.bounds.size.width + 15, view.bounds.size.height / 5, view.bounds.size.width - self.foodImageView.bounds.size.width - self.foodImageView.bounds.origin.x, 20)];
    self.nameLab.font = [UIFont boldSystemFontOfSize:20];
    [view addSubview:self.nameLab];
    
    self.energyLab = [[UILabel alloc] initWithFrame:CGRectMake(self.foodImageView.bounds.size.width + 15, view.bounds.size.height / 5+ 30, view.bounds.size.width / 2, 20)];
    self.energyLab.font = [UIFont boldSystemFontOfSize:20];
    [view addSubview:self.energyLab];
    
    
    self.bigArr = [NSMutableArray array];
    self.energyArr = [NSMutableArray array];
    self.finalTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.finalTableView.delegate = self;
    self.finalTableView.dataSource = self;
    [self.view addSubview:self.finalTableView];
    
    [self.finalTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"final"];
    
    self.finalTableView.tableHeaderView = view;
    [self handleData];

    [self.finalTableView registerClass:[IntroduceCell class] forCellReuseIdentifier:@"introduce"];
    
    [self.finalTableView registerClass:[CompareTableViewCell class] forCellReuseIdentifier:@"compare"];
    [self.finalTableView registerClass:[IngredientTableViewCell class] forCellReuseIdentifier:@"ingredient"];
    self.title = _finalFood.name;
}
//  左侧点击按钮
- (void)leftBarButtonAction:(UIBarButtonItem *)bnt
{
    [self.navigationController popViewControllerAnimated:YES];
    
}
// 右侧点击按钮1
- (void)rightBarButtonAction:(UIBarButtonItem *)bnt
{
    if (self.isCollection == YES) {
        
        [self.foodDB executeUpdate:@"delete from t_foodDetail where code = ?;",self.foodCode];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-aa@3x.png"] style:UIBarButtonItemStyleDone target:self action:@selector(rightBarButtonAction:)];
   
        self.isCollection = !_isCollection;
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"取消收藏" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
        
        
        
    }else{
        
        [self.foodDB executeUpdate:@"insert into t_foodDetail(code, name, thumb_image_url) values (?,?,?);",self.finalFood.code,self.finalFood.name,self.finalFood.thumb_image_url];
        UIImage *image = [UIImage imageNamed:@"iconfont-aa-2@3x.png"];
        image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStyleDone target:self action:@selector(rightBarButtonAction:)];
     
        self.isCollection = !_isCollection;
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示^_^" message:@"成功加入收藏" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
  
}
- (void)rightBarButtonAction2:(UIView *)item
{
    NSString *str = _finalFood.name;
    NSString * imagesStr = _finalFood.thumb_image_url;
    
    NSMutableDictionary *shareParms = [NSMutableDictionary dictionary];
    [shareParms SSDKSetupShareParamsByText:[NSString stringWithFormat:@"我最近在进行健康饮食KeepFiting<%@>",str]
                                    images:@[imagesStr]
                                       url:[NSURL URLWithString:@"http://mob.com"]
                                     title:@"我最近在看:"
                                      type:SSDKContentTypeAuto];
    //进行分享
    [ShareSDK showShareActionSheet:item
                             items:nil
                       shareParams:shareParms
               onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                   switch (state) {
                       case SSDKResponseStateBegin:
                       {
                           NSLog(@"开始分享");
                       }
                           break;
                       case SSDKResponseStateSuccess:
                       {
                           UIAlertController *alentController = [UIAlertController alertControllerWithTitle:@"提示" message:@"分享成功" preferredStyle:UIAlertControllerStyleAlert];
                           UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
                           [alentController addAction:action];
                           [self presentViewController:alentController animated:YES completion:nil];
                       }
                           break;
                       case SSDKResponseStateFail:
                       {
                           UIAlertController *alertController =[UIAlertController alertControllerWithTitle:@"提示" message:@"分享失败'" preferredStyle:UIAlertControllerStyleAlert];
                           UIAlertAction *action =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                           [alertController addAction:action];
                           [self presentViewController:alertController animated:YES completion:nil];
                          
//                           NSLog(@"%@",error);
                       }
                           break;
                       case SSDKResponseStateCancel:
                       {
                           UIAlertController *alertController =[UIAlertController alertControllerWithTitle:@"提示" message:@"取消分享" preferredStyle:UIAlertControllerStyleAlert];
                           UIAlertAction *action =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                           [alertController addAction:action];
                           [self presentViewController:alertController animated:YES completion:nil];                       }
                           break;
                       default:
                           break;
                   }
               }];
 
}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    if (section == 0) {
//        
//        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 20)];
//        UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(50, 0, 100, 20)];
//        lab.text = @"食物简介";
//        lab.textColor = [UIColor redColor];
//        [view addSubview:lab];
//        view.backgroundColor = [UIColor whiteColor];
//        return view;
//    }
//    else
//    {
//        return nil;
//        
//    }
//
//}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }
    if (section == 1&& _foodCompare.target_name != nil) {
        
                    return 1;
       }
    else{
    return self.foodChineseArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        IntroduceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"introduce"];
        switch ([self.finalFood.health_light intValue])
        {
            case 1:
            {
                cell.introduceImageView.image = [UIImage imageNamed:@"kaixin.png"];
                cell.lowLab.text = @"健康推荐";
                cell.lowLab.font = [UIFont boldSystemFontOfSize:12];
                cell.lowLab.textColor = [UIColor colorWithRed:96 / 255.0 green:176 / 255.0 blue:8 / 255.0 alpha:1.0];
//                cell.lowLab
            }
                break;
            case 2:
            {
                cell.introduceImageView.image = [UIImage imageNamed:@"zhengchang.png"];
                cell.lowLab.text = @"适量而食";
                cell.lowLab.font = [UIFont boldSystemFontOfSize:12];
                cell.lowLab.textColor = [UIColor colorWithRed:241 / 255.0 green:134 / 255.0 blue:88 / 255.0 alpha:1.0];            }
                break;
            case 3:
            {
                cell.introduceImageView.image = [UIImage imageNamed:@"jusang.png"];
                cell.lowLab.text = @"您以走远";
                cell.lowLab.font = [UIFont boldSystemFontOfSize:12];
                cell.lowLab.textColor = [UIColor colorWithRed:217 / 255.0 green:52 / 255.0 blue:51 / 255.0 alpha:1.0];
            }
                break;
            default:
                break;
        }
        
        if ([self.finalFood.appraise isEqualToString:@""])
        {
            cell.introduceLab.text = @"暂无简介";
        }
        else
        {
            cell.introduceLab.text = self.finalFood.appraise;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;
    } if (self.foodCompare.target_name != nil&& indexPath.section == 1)
    {
        CompareTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"compare"];
        [cell.compareImageView sd_setImageWithURL:[NSURL URLWithString:self.foodCompare.target_image_url] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
        cell.amount1Lab.text = self.foodCompare.amount1;
        cell.equalLab.text = [NSString stringWithFormat:@"%@%@%@ ≈ %@%@%@",self.foodCompare.amount0,self.foodCompare.unit0,self.finalFood.name,self.foodCompare.amount1,self.foodCompare.unit1,self.foodCompare.target_name];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;
        
    }
    else {
        IngredientTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ingredient"];
        
        cell.chineseLab.text = [self.foodChineseArr objectAtIndex:indexPath.row];
        cell.energyLab.text = [NSString stringWithFormat:@"%@ %@",[self.energyArr objectAtIndex:indexPath.row],[self.danWeiArr objectAtIndex:indexPath.row]];
        if (indexPath.row < 5) {
            
            cell.remarkLab.text = [self.remarkArr objectAtIndex:indexPath.row];
         
        } else {
            cell.remarkLab.text = @"";
        }
       
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }
    
}
  


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_foodCompare.target_name == nil)  {
        return 2;
    }else
    {
        return 3;
    }
    
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (_foodCompare.target_name == nil) {
        NSArray *arr = @[@"食物简介",@"营养元素"];
        return [arr objectAtIndex:section];
    }else{
        NSArray *arr = @[@"食物简介",@"所含热量",@"营养元素"];
        return [arr objectAtIndex:section];
    }
}


- (void)handleData
{
    MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hub.color = [UIColor colorWithRed:0.13 green:0.10 blue:0.10 alpha:0.9];
    hub.removeFromSuperViewOnHide = YES;
    
    hub.delegate = self;
    hub.labelText = @"得之我幸,失之我命,如此安好...";
    NSString *str = [NSString stringWithFormat:@"http://food.boohee.com/fb/v1/foods/%@",self.foodCode];
    
    [NetWorkingCache getUrl:str success:^(id result) {
        self.finalFood = [FoodDetail modelWithDic:result];
        [self.foodImageView sd_setImageWithURL:[NSURL URLWithString:_finalFood.thumb_image_url] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
        self.title = self.finalFood.name;
        self.nameLab.text = _finalFood.name;
        self.energyLab.text = [NSString stringWithFormat:@"%@大卡/100克",_finalFood.weight];
        [self.bigArr addObject:_finalFood];
        
        self.foodCompare = [Compare modelWithDic:_finalFood.compare];
        
        self.foodImgredient  = [Ingredient modelWithDic:_finalFood.ingredient];
        
        self.foodChineseArr = @[@"热量",@"蛋白质",@"脂肪",@"碳水化合物",@"膳食纤维",@"维生素A",@"维生素C",@"维生素E",@"胡萝卜素",@"维生素B1",@"维生素b2",@"烟酸",@"胆固醇",@"镁",@"钙",@"铁",@"锌",@"铜",@"锰",@"钾",@"磷",@"纳",@"硒"];
        
        self.danWeiArr = @[@"大卡",@"克",@"克",@"克",@"克",@"微克",@"毫克",@"微克",@"微克",@"毫克",@"毫克",@"毫克",@"毫克",@"毫克",@"毫克",@"毫克",@"毫克", @"毫克",@"毫克",@"毫克",@"毫克",@"毫克",@"微克"];
        
        
        NSArray *englishArr = [[NSArray alloc]initWithObjects:@"calory",@"protein",@"fat",@"carbohydrate",@"fiber_dietary",@"vitamin_a",@"vitamin_c", @"vitamin_e",@"carotene",@"thiamine",@"lactoflavin",@"niacin",@"cholesterol",@"magnesium",@"calcium",@"iron",@"zinc",@"copper",@"manganese",@"kalium",@"phosphor",@"natrium",@"selenium", nil];
        for (NSString *key in englishArr)
        {
            
            NSString *value = [self.finalFood.ingredient objectForKey:key];
            if ([value isEqualToString:@""])
            {
                value = @"--";
            }
            
            [self.energyArr addObject: value];
    }

        self.remarkArr = [NSMutableArray array];
        for (NSInteger i = 0; i < 5; i++)
        {
            NSString *key = [englishArr objectAtIndex:i];
            NSString *value = [self.finalFood.lights objectForKey:key];
            if (value == nil)
            {
                value = @"  ";
            }
            [self.remarkArr addObject:value];
        }
   
        [self.finalTableView reloadData];
        [hub hide:YES];
    } failure:^(NSError *error) {
        
    }];
  
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
            CGRect rect =  [self.finalFood.appraise boundingRectWithSize:CGSizeMake(tableView.bounds.size.width-(10 + 50 + 10), 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17]} context:nil];
            return (rect.size.height + 20 + 1)> 95 ? (rect.size.height + 20 + 1) : 95;
    }
    if (_foodCompare.target_name != nil && indexPath.section == 1) {
        return 100;
    }
    
    else
    {
        return 30;
    }
  
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
